package com.liangxiao.wifichat.fragment;

import android.app.Fragment;
import android.content.Context;
import android.content.SyncStatusObserver;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.liangxiao.wifichat.MainActivity;
import com.liangxiao.wifichat.R;
import com.liangxiao.wifichat.WifiApManager;
import com.liangxiao.wifichat.WifiChatService;

import java.util.ArrayList;
import java.util.List;
import android.os.*;
import android.util.*;

/**
 * 备注:
 *
 * @author hmb
 * @version 1.0
 * @since 2015/9/18 0:34
 */
public class MainFragment extends Fragment implements View.OnClickListener, AdapterView.OnItemClickListener {

    private EditText et;
    private ListView listView;
    private Adapter adapter;

    private List<ScanResult> list = new ArrayList<>();

    private WifiApManager ap;
    private WifiManager wifi;
    private WifiChatService mService;

    public static MainFragment getInstance(WifiChatService service) {
        MainFragment fragment = new MainFragment();
        fragment.mService = service;
        fragment.wifi = service.getWifiManager();
        fragment.ap = service.getApManager();
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.main_fragment, container, false);
        et = (EditText) view.findViewById(R.id.mainEditText);

        listView = (ListView) view.findViewById(R.id.listView);
        adapter = new Adapter();
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);
        Button open = (Button) view.findViewById(R.id.open);
        View refresh = view.findViewById(R.id.refresh);
        refresh.setOnClickListener(this);
        open.setOnClickListener(this);
        if (mService.getApManager().isWifiApEnabled()) {
            mService.start();
        } else {
            WifiManager wifi = mService.getWifiManager();
            if (!wifi.isWifiEnabled()){
                wifi.setWifiEnabled(true);
            }
            mService.scan();
        }

        /*Button reset = (Button) view.findViewById(R.id.reset);
        reset.setOnClickListener(this);

        Button close = (Button) view.findViewById(R.id.close);
        close.setOnClickListener(this);

        Button send = (Button) view.findViewById(R.id.send);
        send.setOnClickListener(this);

        Button connectWIFI = (Button) view.findViewById(R.id.connect_wifi);
        connectWIFI.setOnClickListener(this);

        Button connect = (Button) view.findViewById(R.id.connect);
        connect.setOnClickListener(this);*/
        return view;
    }

    public void setScanResult(List<ScanResult> result) {
        list.clear();
        for (ScanResult s : result) {
            System.out.println(s.SSID);
            if (s.SSID.contains(WifiApManager.DEFAULT_SSID_PREFIX)) {
                list.add(s);
            }
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.open:
                ap.openAP(et.getText().toString(), "123456789");

                mService.start();

                break;
            case R.id.refresh:
                mService.scan();
                break;
            /*case R.id.close:
            ap.closeAp(false);
            break;
            case R.id.send:
            mService.write(msg.getText().toString().getBytes());
            break;
            case R.id.connect_wifi:
                boolean b = ap.connect(et.getText().toString(), "123456789");
                Toast.makeText(getActivity(), b + "正在连接 " + et.getText().toString(), Toast.LENGTH_SHORT).show();
                break;
            case R.id.connect:
                showToast("server ip :" + ap.getServerIpAdress());
                mService.connect(ap.getServerIpAdress());
                break;

            case R.id.reset:
                ap.resetAp();
                break;*/
            default:
                break;
        }
    }

    public void showToast(String msg) {
        Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
        
	
			ScanResult result = list.get(position);
        if (ap.connect(result.SSID.replace(WifiApManager.DEFAULT_SSID_PREFIX, ""), WifiApManager.DEFAULT_PASSWORD)) {
            showToast("连接成功，尝试握手");
			//int count = 0;
			//while(count < 3&&wifi.getWifiState() != WifiManager.WIFI_STATE_ENABLED){
            	//mService.connect(ap.getServerIpAdress());
				Log.d("MainFragment","zhengzai lianjie wifi");
			//	count++;
				//SystemClock.sleep(4000);
			//}
			}
		new Thread(new Runnable(){
				public void run(){
			int count = 0;
			do{
			
			if(mService.getState() == WifiChatService.STATE_CONNECTED || count > 3){
				return;
			}
			mService.connect(ap.getServerIpAdress());
			count++;
			SystemClock.sleep(1500);
			}while(true);
        }
		}
		).start();
    }


    private class Adapter extends BaseAdapter {

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = LayoutInflater.from(getActivity()).inflate(R.layout.scan_result_item, parent, false);
            TextView name = (TextView) convertView.findViewById(R.id.name);
            LinearLayout loading = (LinearLayout) convertView.findViewById(R.id.loading);

            name.setText(list.get(position).SSID.replace(WifiApManager.DEFAULT_SSID_PREFIX, ""));

            return convertView;
        }
    }
}
